#include "SI7021.h"




void SI7021_Init(void)
{
	IIC_Init();
}

//读取温湿度，返回0成功，其他失败
u8 SI7021_Read(float *temp,float *hum)
{
	u8 r=0;
	u16 t=0,h=0;
	
	r += SI7021_Measure(SI7021_TEMP_HOLD,&t);
	r += SI7021_Measure(SI7021_HUMI_HOLD,&h);
	
	*temp = t*175.72/65536-46.85;
	*hum  = (h&~3)*125.0/65536-6;
	
	return r;
}


//读取温湿度，返回0成功，其他失败
u8 SI7021_Read_Byte(u16 *temp,u16 *hum)
{
	u8 r=0;
	r += SI7021_Measure(SI7021_TEMP_HOLD,temp);
	r += SI7021_Measure(SI7021_HUMI_HOLD,hum);
	
	*hum &= ~0x03;
	
	//*temp = t*175.72/65536-46.85;
	//*hum  = (h&~3)*125.0/65536-6;
	
	return r;
}


//开始测量，返回0成功，其他失败
u8 SI7021_Measure(u8 cmd,u16* val)
{
	u8 data[2];
	u8 error=0;
	
	IIC_Start();						//S
	IIC_WriteByte(0x80);				//Slave Addr W
	error += IIC_Wait_Ack();			//--A
	IIC_WriteByte(cmd);	//CMD		
	error += IIC_Wait_Ack();			//--A
	
	IIC_Start();						//Sr
	IIC_WriteByte(0x81);				//Slave Addr R
	error += IIC_Wait_Ack();			//--A
	
	delay_ms(20);

	data[1] = IIC_ReadByte(1);			//MS Byte + A
	data[0] = IIC_ReadByte(0);			//MS Byte + NA

	IIC_Stop();
	
	*val = (u16)(data[1]<<8|data[0]);
	
	return error;
}




